package org.ysling.litemall.core.tasks;
/**
 *  Copyright (c) [ysling] [927069313@qq.com]
 *  [litemall-plus] is licensed under Mulan PSL v2.
 *  You can use this software according to the terms and conditions of the Mulan PSL v2.
 *  You may obtain a copy of Mulan PSL v2 at:
 *              http://license.coscl.org.cn/MulanPSL2
 *  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 *  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 *  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *  See the Mulan PSL v2 for more details.
 */
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ysling.litemall.core.service.ActionLogService;
import org.ysling.litemall.core.system.SystemConfig;
import org.ysling.litemall.core.tasks.service.Task;
import org.ysling.litemall.core.tenant.config.CustomTenantLineHandler;
import org.ysling.litemall.core.utils.BeanUtil;
import org.ysling.litemall.core.weixin.pay.WeixinPayCoreService;
import org.ysling.litemall.db.constant.OrderConstant;
import org.ysling.litemall.db.domain.*;
import org.ysling.litemall.db.service.*;

import java.time.LocalDateTime;

/**
 * 订单自动确认收货延时队列
 */
public class OrderUnconfirmedTask extends Task {

    private final Log logger = LogFactory.getLog(OrderUnconfirmedTask.class);
    private final Integer orderId;
    private Integer tenantId = 0;

    public OrderUnconfirmedTask(Integer orderId, long delayInMilliseconds){
        super("OrderUnconfirmedTask-" + orderId, delayInMilliseconds);
        this.orderId = orderId;
        this.getTenantId();
    }

    public OrderUnconfirmedTask(Integer orderId){
        super("OrderUnconfirmedTask-" + orderId, SystemConfig.getOrderUnconfirmed() * 24 * 60 * 60 * 1000);
        this.orderId = orderId;
        this.getTenantId();
    }

    private void getTenantId() {
        LitemallOrderService orderService = BeanUtil.getBean(LitemallOrderService.class);
        LitemallOrder order = orderService.findById(orderId);
        this.tenantId = order.getTenantId();
    }

    @Override
    public void run() {
        logger.info(String.format("系统处理延时任务 -> [开始-订单自动收货] [任务ID-%s]" , this.orderId));

        ActionLogService logService = BeanUtil.getBean(ActionLogService.class);
        LitemallUserService userService = BeanUtil.getBean(LitemallUserService.class);
        LitemallOrderService orderService = BeanUtil.getBean(LitemallOrderService.class);
        LitemallBrandService brandService = BeanUtil.getBean(LitemallBrandService.class);
        WeixinPayCoreService payCoreService = BeanUtil.getBean(WeixinPayCoreService.class);
        //添加当前租户
        CustomTenantLineHandler.setTenantId(this.tenantId.longValue());

        logService.logOrderSucceed("系统处理延时任务",String.format("[开始-订单自动收货] [任务ID-%s]" , this.orderId));

        LitemallOrder order = orderService.findById(this.orderId);
        //判断是否满足收货条件
        if(order == null || !OrderConstant.isShipStatus(order)) return;
        //获取店铺信息
        LitemallBrand brand = brandService.findById(order.getBrandId());
        if (brand == null) throw new RuntimeException("店铺信息获取失败");

        // 设置订单已收货状态
        order.setConfirmTime(LocalDateTime.now());
        order.setOrderStatus(OrderConstant.STATUS_AUTO_CONFIRM);
        if (orderService.updateVersionSelective(order) == 0) {
            throw new RuntimeException("订单 ID=" + order.getId() +"数据更新失败");
        } else {
            logger.info("订单 ID=" + order.getId() + " 已经超期自动确认收货");
        }

        //获取店铺所有者向店家打款
        if (brand.getUserId() == null || brand.getUserId() <= 0){
            logger.info("系统自动打款---未找到店铺用户---" + orderId);
        } else {
            //获取店铺用户
            LitemallUser user = userService.findById(brand.getUserId());
            //商家付款到零钱
            payCoreService.merchantsPayToChange(user , order);
        }

        logger.info(String.format("系统处理延时任务 -> [结束-订单自动收货] [任务ID-%s]" , this.orderId));
        logService.logOrderSucceed("系统处理延时任务",String.format("[结束-订单自动收货] [任务ID-%s]" , this.orderId));
    }
}
